package cn.magic.basic.service.impl;

import cn.magic.basic.constants.BaseConstants;
import cn.magic.basic.dto.LoginDto;
import cn.magic.basic.exception.BusinessException;
import cn.magic.basic.service.ILoginService;
import cn.magic.basic.utils.*;
import cn.magic.user.domain.Logininfo;
import cn.magic.user.domain.User;
import cn.magic.user.domain.Wxuser;
import cn.magic.user.dto.WxDto;
import cn.magic.user.mapper.LogininfoMapper;
import cn.magic.user.mapper.UserMapper;
import cn.magic.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
    * @Title: account
    * @Description: 根据账号密码登录
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/7 16:49
    * @Parameters: [loginDto]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        String username = loginDto.getUsername();
        // 1.非空判断
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(type) || StringUtils.isEmpty(username)){
            throw new BusinessException("参数不能为空");
        }
        // 2.根据账号&type查询用户，字段对应有三个username or phone or email and type
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        // 3.判断账号是否存在
        if (logininfo == null){
            throw new BusinessException("账号或者密码错误");
        }
        // 4.判断密码是否一致，需要加盐加密处理
        // 将前端传递的密码 和 数据库中的盐值 与数据库中的加盐密码对比
        String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        if (!logininfo.getPassword().equals(passwordTmp)){
            throw new BusinessException("账号或者密码错误");
        }
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid && logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 8.将uuid&&logininfo存入到map中，返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo", logininfo);


        return map;
    }


    /**
    * @Title: quit
    * @Description: 退出登录
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/9 13:06
    * @Parameters: [request]
    * @Return void
    */
    @Override
    public void quit(HttpServletRequest request) {
        String token = request.getHeader("token");
        redisTemplate.delete(token);

    }


    /**
    * @Title: sendMobileCode
    * @Description: 发送验证码登录
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/9 17:12
    * @Parameters: [loginDto]
    * @Return void
    */
    @Override
    public void sendMobileCode(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        String codeValue = loginDto.getCodeValue();
        String imageCodeKey = loginDto.getImageCodeKey();
        // 非空校验
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(imageCodeKey) ||
                StringUtils.isEmpty(type) ||
                StringUtils.isEmpty(codeValue)) {
            throw new BusinessException("参数不正确！请正确输入");
        }
        // 根据前端传递的token，key 查询redis中的value
        Object imageCode = redisTemplate.opsForValue().get(imageCodeKey);
        // 判断redis中是否有前端传递过来的token，对应的value
        if (imageCode == null){
            throw  new BusinessException("图形码已失效，请重新获取");
        }
        // 如果存在比较图形验证码的是否相等
        if (!imageCode.toString().equalsIgnoreCase(codeValue)){
            throw  new BusinessException("图形码不一致 ，请重新输入");
        }
        // 判断账号是否存在
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);

        if (logininfo ==null){
            throw new BusinessException("账号不存在，请重新输入");

        }
        // 根据不同的参数发送不同的信息
        String businessKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + username;
        if (username.indexOf("@") == -1){
            // 获取验证码
            Object smsCode = getCode(businessKey);
            // SmsUtil.sendSms(username, "您的短信验证码是：" + smsCode);
            System.out.println("您的短信验证码是：" + smsCode);

        } else {
            // 获取验证码
            Object smsCode = getCode(businessKey);
            // 发送邮箱
            //
            // EmailUtil.sendEmail();

        }
    }

    /**
    * @Title: codeLogin
    * @Description: 验证码登录
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/9 18:19
    * @Parameters: [loginDto]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> codeLogin(LoginDto loginDto) {
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        String username = loginDto.getUsername();
        // 1.非空判断
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(type) || StringUtils.isEmpty(username)){
            throw new BusinessException("参数不能为空");
        }
        // 2.根据账号&type查询用户，字段对应有三个username or phone or email and type
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        // 3.判断账号是否存在
        if (logininfo == null){
            throw new BusinessException("账号或者密码错误");
        }
        // 4.判断密码是否一致，需要加盐加密处理
        // 将前端传递的密码 和 数据库中的盐值 与数据库中的加盐密码对比
        /*String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        if (!logininfo.getPassword().equals(passwordTmp)){
            throw new BusinessException("账号或者密码错误");
        }*/
        // 5.生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 6.将uuid && logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        // 7.把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 8.将uuid&&logininfo存入到map中，返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo", logininfo);

        return map;
    }


    /**
    * @Title: getCode
    * @Description: 判断验证是否存在以获取验证码，并设置给redis
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/9 18:02
    * @Parameters: [businessKey]
    * @Return java.lang.Object
    */
    private Object getCode(String businessKey) {
        Object smsCode = redisTemplate.opsForValue().get(businessKey);
        if (smsCode == null) {
            smsCode = StrUtils.getComplexRandomString(4);
        } else {
            // 获取过期时间
            Long expirationTime = redisTemplate.opsForValue().getOperations().getExpire(businessKey);
            if (expirationTime > 4 * 60) {
                throw new BusinessException("请一分钟之后再获取");
            }
        }
        redisTemplate.opsForValue().set(businessKey, smsCode, 5, TimeUnit.MINUTES);
        return smsCode;
    }

    /**
     * @Title: wechat
     * @Description: 微信登录接口
     * @Author: Mr.pc
     * @Version: 1.0
     * @Date:  2022/7/10 17:20
     * @Parameters: [wxDto]
     * @Return cn.magic.basic.utils.AjaxResult
     */
    @Override
    public AjaxResult wechat(WxDto wxDto) {
        String code = wxDto.getCode();
        // 非空校验
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数不能为空");
        }
        // 根据code调用微信API获取access_token&openId
        // 根据APPID和SECRET和CODE拼接地址
        String tokenUrl = BaseConstants.WxConstant.TOKEN_URL
                .replace("APPID", BaseConstants.WxConstant.APPID)
                .replace("SECRET", BaseConstants.WxConstant.SECRET)
                .replace("CODE", code);
        // 根据工具类httputil发送get请求，得到的是我们需要的openid和access_token
        String jsonObjStr = HttpUtil.httpGet(tokenUrl);
        // 将string类型的jsonObjStr转换为JSONObject格式
        JSONObject jsonObj = JSONObject.parseObject(jsonObjStr);
        // 3.根据openId查询wxUser表，看微信用户是否存在并且绑定账号
        Wxuser wxuser = wxuserMapper.loadByOpenId(jsonObj.getString("openid"));
        // 3.1.存在并且绑定，让用户直接免密登录
        // 判断wxuser存在，并且绑定了userID说明存在并且绑定
        if (wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            // 5.生成UUID作为key
            String token = UUID.randomUUID().toString();
            // 6.将uuid && logininfo设置到redis中，设置30分钟有效期
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

            // 7.把Logininfo对象的敏感信息置为空，作为value
            logininfo.setSalt("");
            logininfo.setPassword("");
            // 8.将uuid&&logininfo存入到map中，返回给前端
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo", logininfo);
            return AjaxResult.me().setResultObj(map);
        }
        // 不存在，传递access_token & openId到页面，并且success=false&message=nobinder
        String paramStr = "?accessToken=" + jsonObj.getString("access_token") + "&openId=" + jsonObj.getString("openid");
        return AjaxResult.me().setSuccess(false).setMessage("nobinder").setResultObj(paramStr);
    }

    /**
    * @Title: binder
    * @Description: 微信绑定登录
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/10 18:54
    * @Parameters: [wxDto]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> binder(WxDto wxDto) {
        String verifyCode = wxDto.getVerifyCode();
        String phone = wxDto.getPhone();
        String openId = wxDto.getOpenId();
        String accessToken = wxDto.getAccessToken();
        // 非空校验
        if (   StringUtils.isEmpty(verifyCode)
            || StringUtils.isEmpty(phone)
            || StringUtils.isEmpty(openId)
            || StringUtils.isEmpty(accessToken)){
            throw new BusinessException("参数不能为空");
        }
        // 手机验证码校验
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_BINDER_KEY + phone;
        Object phoneCodeKeyValue = redisTemplate.opsForValue().get(phoneCodeKey);
        // 3.判断验证码是否正确
        String phoneCode = phoneCodeKeyValue.toString().split(":")[1];
        if (!phoneCode.equals(verifyCode)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 3.根据手机号查询用户是否存在
        User user = userMapper.loadByphone(phone);
        // 不存在：初始化user&logininfo并保存
        Logininfo logininfo = null;
        if (user == null){
            // 1.初始化user对象
            user = smsCodeDto2User(phone);
            // 2.拷贝user对象到logininfo中
            logininfo = user2Logininfo(user);
            // 3.保存logininfo
            logininfoMapper.save(logininfo);
            // 4.设置logininfo主键到user对象中
            user.setLogininfoId(logininfo.getId());
            // 5.保存user对象
            userMapper.save(user);

        }else {
            // 存在查询loginnifo
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        // 根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseConstants.WxConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpUtil.httpGet(wxUserUrl);
        // 通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 返回成功登录map
        // 生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;

    }

    /** 
    * @Title: user2Logininfo
    * @Description: 将user表数据拷贝到logininfo
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/10 20:43  
    * @Parameters: [user]
    * @Return cn.magic.user.domain.Logininfo
    */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    /** 
    * @Title: smsCodeDto2User
    * @Description: 初始化user表
    * @Author: Mr.pc
    * @Version: 1.0
    * @Date:  2022/7/10 20:42  
    * @Parameters: [phone]
    * @Return cn.magic.user.domain.User
    */
    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        //  此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }
    


}
